package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;

import android.app.Dialog;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.SeekBar;
import android.widget.TextView;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import VideoHandle.EpEditor;
import VideoHandle.OnEditorListener;
import flc.ast.BaseAc;
import flc.ast.Content;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.ColorAdapter;
import flc.ast.bean.ColorBean;
import flc.ast.databinding.ActivityVideoBgBinding;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.TimeUtil;

public class VideoBgActivity extends BaseAc<ActivityVideoBgBinding> {

    public static String videoPath;
    private List<ColorBean> listColor = new ArrayList<>();
    public static ColorAdapter colorAdapter;
    private String bgColor="";
    private int oldPosition;
    private long videoLength;
    private Dialog myTipDialog;
    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            mDataBinding.tvVideoLeftText.setText(TimeUtil.getMmss(mDataBinding.videoView.getCurrentPosition()));
            mDataBinding.sbVideoPlay.setProgress(Integer.parseInt(TimeUtils.millis2String(mDataBinding.videoView.getCurrentPosition(), "ss")));
            mHandler.postDelayed(this, 500);
        }
    };


    @Override
    protected int onCreate() {
        return R.layout.activity_video_bg;
    }

    @Override
    public void onBackPressed() {
        myTipDialog.show();
    }

    @Override
    protected void initView() {
        mDataBinding.ivVideoBgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivVideoPlay.setOnClickListener(this);
        mDataBinding.tvVideoBgSave.setOnClickListener(this);
        tipDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()){
            case R.id.ivVideoPlay://播放/暂停
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.icon_bf);
                    mDataBinding.videoView.pause();
                    stopTime();
                } else {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.icon_zt);
                    mDataBinding.videoView.start();
                    startTime();
                }
                break;
            case R.id.tvVideoBgSave:
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.icon_bf);
                    mDataBinding.videoView.pause();
                    stopTime();
                }
                saveVideo();
                break;
            //提示弹框
            case R.id.tvDialogTipCancel://取消
                myTipDialog.dismiss();
                break;
            case R.id.tvDialogTipRight://确定
                myTipDialog.dismiss();
                finish();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        bgColor=colorAdapter.getItem(position).getColor();
        colorAdapter.getItem(oldPosition).setSelect(false);
        colorAdapter.notifyItemChanged(oldPosition);
        oldPosition=position;
        colorAdapter.getItem(position).setSelect(true);
        colorAdapter.notifyItemChanged(position);
        mDataBinding.rlVideoBg.setBackgroundColor(Color.parseColor(bgColor));
    }

    @Override
    protected void initData() {
        if (TextUtils.isEmpty(videoPath)) return;
        videoLength = MediaUtil.getDuration(videoPath);
        setPlayer();
        listColor.add(new ColorBean("#FFFFFF", true));
        listColor.add(new ColorBean("#D8D8D8", false));
        listColor.add(new ColorBean("#2D2D2D", false));
        listColor.add(new ColorBean("#FF8F8F", false));
        listColor.add(new ColorBean("#FFBE46", false));
        listColor.add(new ColorBean("#FFEB47", false));
        listColor.add(new ColorBean("#9BDC3D", false));
        listColor.add(new ColorBean("#45C965", false));
        listColor.add(new ColorBean("#4FADB6", false));
        listColor.add(new ColorBean("#3C49DD", false));
        listColor.add(new ColorBean("#6140AA", false));
        listColor.add(new ColorBean("#C050DE", false));
        listColor.add(new ColorBean("#E74F8E", false));
        listColor.add(new ColorBean("#C82222", false));
        mDataBinding.rvVideoBgColorList.setLayoutManager(new GridLayoutManager(mContext, 6));
        colorAdapter = new ColorAdapter();
        mDataBinding.rvVideoBgColorList.setAdapter(colorAdapter);
        colorAdapter.setList(listColor);
        bgColor=listColor.get(0).getColor();
        mDataBinding.rlVideoBg.setBackgroundColor(Color.parseColor(bgColor));
        colorAdapter.setOnItemClickListener(this);
    }

    private void saveVideo(){
        String path = FileUtil.generateFilePath(Content.myTemp, getString(R.string.unit_mp4));//输出路径
        EpEditor.insertBgColor(videoPath, 800, 1080, bgColor, path, new OnEditorListener() {
            @Override
            public void onSuccess() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissDialog();
                        FileP2pUtil.copyPrivateVideoToPublic(mContext, path);
                        dismissDialog();
                        ToastUtils.showShort(getString(R.string.save_suc));
                        startActivity(HomeActivity.class);
                    }
                });
            }

            @Override
            public void onFailure() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissDialog();
                        ToastUtils.showShort(R.string.add_bg_def);
                    }
                });
            }

            @Override
            public void onProgress(float progress) {
                showDialog(getString(R.string.save_video_ing)
                        + new DecimalFormat(getString(R.string.unit_num1)).format(progress * 100)
                        + "%");
            }
        });
    }

    //设置播放器
    private void setPlayer() {
        mHandler = new Handler();
        //设置seekbar
        mDataBinding.tvVideoLeftText.setText("00:00");
        mDataBinding.tvVideoRightText.setText(TimeUtil.getMmss(videoLength));
        mDataBinding.sbVideoPlay.setMax(Integer.parseInt(TimeUtils.millis2String(videoLength, "ss")));
        mDataBinding.sbVideoPlay.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mDataBinding.videoView.seekTo(seekBar.getProgress());
            }
        });
        //设置播放器
        mDataBinding.videoView.setVideoPath(videoPath);
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {  // 播放完成的监听
                mDataBinding.tvVideoLeftText.setText("00:00");
                mDataBinding.tvVideoRightText.setText(TimeUtil.getMmss(videoLength));
                mDataBinding.sbVideoPlay.setProgress(0);
                mDataBinding.ivVideoPlay.setImageResource(R.drawable.icon_bf);
                mp.seekTo(1);
                stopTime();
            }
        });
        //开始播放视频
        mDataBinding.ivVideoPlay.setImageResource(R.drawable.icon_zt);
        mDataBinding.videoView.start();
        startTime();
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

    @Override
    protected void onStop() {
        super.onStop();
        mDataBinding.ivVideoPlay.setImageResource(R.drawable.icon_bf);
        mDataBinding.videoView.pause();
        stopTime();
    }

    //提示弹框
    private void tipDialog() {
        myTipDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_tip, null);
        myTipDialog.setContentView(inflate);
        myTipDialog.setCancelable(true);
        Window dialogWindow = myTipDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.8);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView cancel = inflate.findViewById(R.id.tvDialogTipCancel);
        TextView right = inflate.findViewById(R.id.tvDialogTipRight);
        cancel.setOnClickListener(this);
        right.setOnClickListener(this);
    }

}